<?php

use Symfony\Component\Filesystem\Filesystem;

 class EduSohoUpgrade extends AbstractUpdater
 {
     public function update()
     {
        $this->getConnection()->beginTransaction();
        try{
            $this->updateScheme();
            $this->installRouting();
            $this->installAssets();

            $this->createService('System.SettingService')->set('vip', array(
              'enabled'=> 1,
              'upgrade_min_day' => 30,
            ));

            $existBlock = $this->getBlockService()->getBlockByCode('vip_banner');

            if (!$existBlock) {
              $block = $this->getBlockService()->createBlock(array(
                  'code'=>'vip_banner',
                  'title'=>'会员专区顶部轮播'
              ));
              $content = <<<'EOD'
<a href="#"><img src="http://open.edusoho.com/assets/img/edusoho-demo/vip-banner-1.jpg" /></a>
<a href="#"><img src="http://open.edusoho.com/assets/img/edusoho-demo/vip-banner-2.jpg" /></a>
EOD;
              $this->getBlockService()->updateContent($block['id'], $content);
              
            }

            $this->getConnection()->commit();
        } catch(\Exception $e) {
            $this->getConnection()->rollback();
            throw $e;
        }
     }

    private function getBlockService()
    {
      return $this->createService('Content.BlockService');
    }

    public function installRouting()
    {
        $config = <<<EOT


vip_web:
    resource: "@VipBundle/Resources/config/routing.yml"
    prefix:   /

vip_admin:
    resource: "@VipBundle/Resources/config/routing_admin.yml"
    prefix:   /admin
EOT;
        $filepath = $this->kernel->getParameter('kernel.root_dir') . '/config/routing_plugins.yml';
        file_put_contents($filepath, $config, FILE_APPEND);
    }

    private function installAssets()
    {
        $rootDir = realpath($this->kernel->getParameter('kernel.root_dir') . '/../');

        $originDir = "{$rootDir}/plugins/Vip/VipBundle/Resources/public";
        $targetDir = "{$rootDir}/web/bundles/vip";

        $filesystem = new Filesystem();

        if ($filesystem->exists($targetDir)) {
            $filesystem->remove($targetDir);
        }

        $filesystem->mirror($originDir, $targetDir, null, array('override' => true, 'delete' => true));
    }


     private function updateScheme()
     {
        $connection = $this->getConnection();

        $connection->exec("DROP TABLE IF EXISTS `vip`;");
        $connection->exec("
            CREATE TABLE `vip` (
              `id` int(10) NOT NULL AUTO_INCREMENT,
              `userId` int(10) NOT NULL,
              `levelId` int(10) unsigned NOT NULL,
              `deadline` int(10) unsigned NOT NULL,
              `boughtType` enum('new','upgrade','renew','edit') NOT NULL COMMENT '购买类型',
              `boughtTime` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '购买时间',
              `boughtDuration` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '购买时长',
              `boughtUnit` enum('month','year') NOT NULL COMMENT '开通方式按月、按年',
              `boughtAmount` float(10,2) NOT NULL DEFAULT '0.00',
              `orderId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '购买会员的订单ID',
              `operatorId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '管理员操作时为管理员用户ID',
              `createdTime` int(10) DEFAULT '0',
              PRIMARY KEY (`id`),
              UNIQUE KEY `userId` (`userId`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='会员表';");

        $connection->exec("DROP TABLE IF EXISTS `vip_history`;");
        $connection->exec("
            CREATE TABLE `vip_history` (
              `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
              `userId` int(10) unsigned NOT NULL COMMENT '购买用户',
              `levelId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '会员类型',
              `deadline` int(10) unsigned NOT NULL DEFAULT '0',
              `boughtType` enum('new','upgrade','renew','edit','cancel') NOT NULL COMMENT '购买类型',
              `boughtTime` int(10) unsigned NOT NULL DEFAULT '0',
              `boughtDuration` int(10) unsigned NOT NULL DEFAULT '0',
              `boughtUnit` enum('none','month','year') NOT NULL DEFAULT 'none',
              `boughtAmount` float(10,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '购买金额',
              `orderId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '购买会员的订单ID',
              `operatorId` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '管理员操作时为管理员用户ID',
              `createdTime` int(10) unsigned NOT NULL DEFAULT '0',
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='会员记录表';");

        $connection->exec("DROP TABLE IF EXISTS `vip_level`;");
        $connection->exec("
            CREATE TABLE `vip_level` (
              `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
              `seq` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '序号',
              `name` varchar(64) NOT NULL DEFAULT '' COMMENT '会员类型名称',
              `icon` varchar(255) NOT NULL DEFAULT '' COMMENT '示意图标',
              `picture` varchar(255) NOT NULL DEFAULT '' COMMENT '展示图片',
              `monthPrice` float(10,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '月费价格',
              `yearPrice` float(10,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '年费价格',
              `description` text COMMENT '一句话描述',
              `freeLearned` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '是否免费学习课程',
              `enabled` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '状态',
              `createdTime` int(10) unsigned NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='会员类型表';
        ");
     }

 }


 abstract class AbstractUpdater
 {
    protected $kernel;
    public function __construct ($kernel)
    {
        $this->kernel = $kernel;
    }

    public function getConnection()
    {
        return $this->kernel->getConnection();
    }

    protected function createService($name)
    {
        return $this->kernel->createService($name);
    }

    protected function createDao($name)
    {
        return $this->kernel->createDao($name);
    }

    abstract public function update();
   
 }
